@echo off
setlocal enabledelayedexpansion

:: 配置参数
set SHELL=cmd
set BUILD_IMAGE_SERVER=golang:1.22
set BUILD_IMAGE_WEB=node:20
set PROJECT_NAME=github.com/flipped-aurora/gin-vue-admin/server
set CONFIG_FILE=config.yaml
set IMAGE_NAME=gva
set REPOSITORY=registry.cn-hangzhou.aliyuncs.com/!IMAGE_NAME!
set TAGS_OPT=latest
set PLUGIN=email

:: 入口点
if "%~1"=="" (
    echo Usage: build.bat [target]
    echo Available targets: build, build-web, build-server, build-image-web, build-image-server, doc, plugin
    exit /b
)

call :%~1
exit /b

:build
call :build-web
call :build-server
docker run --name build-local --rm -v %cd%:/go/src/!PROJECT_NAME! -w /go/src/!PROJECT_NAME! !BUILD_IMAGE_SERVER! make build-local
exit /b

:build-web
docker run --name build-web-local --rm -v %cd%:/go/src/!PROJECT_NAME! -w /go/src/!PROJECT_NAME! !BUILD_IMAGE_WEB! make build-web-local
exit /b

:build-server
docker run --name build-server-local --rm -v %cd%:/go/src/!PROJECT_NAME! -w /go/src/!PROJECT_NAME! !BUILD_IMAGE_SERVER! make build-server-local
exit /b

:build-image-web
cd web
docker build -t !REPOSITORY!/web:!TAGS_OPT! .
cd ..
exit /b

:build-image-server
cd server
docker build -t !REPOSITORY!/server:!TAGS_OPT! .
cd ..
exit /b

:build-local
if exist build rmdir /s /q build
if exist .dockerenv (
    echo "OK!"
) else (
    call :build-web-local
    call :build-server-local
)
mkdir build
xcopy /e /y web\dist build\dist
copy server\server build
xcopy /e /y server\resource build\resource
exit /b

:build-web-local
cd web
if exist dist rmdir /s /q dist
yarn config set registry http://mirrors.cloud.tencent.com/npm/
yarn install
yarn build
cd ..
exit /b

:build-server-local
cd server
if exist server del server
go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn,direct
go env -w CGO_ENABLED=0
go env
go mod tidy
go build -ldflags "-B 0x^>nul & set /p "=."<nul & for /l %%N in (1,1,20) do set /p "=%%random%%"<nul" -X main.Version=!TAGS_OPT! -v
cd ..
exit /b

:image
call :build
docker build -t !REPOSITORY!/gin-vue-admin:!TAGS_OPT! -f deploy\docker\Dockerfile .
exit /b

:images
call :build
call :build-image-web
call :build-image-server
docker build -t !REPOSITORY!/all:!TAGS_OPT! -f deploy\docker\Dockerfile .
exit /b

:doc
cd server
swag init
cd ..
exit /b

:plugin
if exist .plugin rmdir /s /q .plugin
mkdir .plugin\!PLUGIN!\server\plugin
mkdir .plugin\!PLUGIN!\web\plugin

if exist server\plugin\!PLUGIN! (
    xcopy /e /y server\plugin\!PLUGIN! .plugin\!PLUGIN!\server\plugin
)
if exist web\src\plugin\!PLUGIN! (
    xcopy /e /y web\src\plugin\!PLUGIN! .plugin\!PLUGIN!\web\plugin
)

cd .plugin
zip -r !PLUGIN!.zip !PLUGIN!
move !PLUGIN!.zip ..
cd ..
exit /b

endlocal